import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {View, Input, Picker, Button, Textarea, ScrollView} from '@tarojs/components'
import {AtButton, AtDrawer, AtModal, AtModalHeader, AtIcon, AtModalContent, AtModalAction} from 'taro-ui'
import {http} from '../../utils/http'
import NewIcon from '../productForm/components/icon';
import {
  SUPPLIER_GOODS_PAGE,
  GOODSCOMPILEDATA,
  GOODSSITELIST,
  SUPPLIER_GOODS_SUPPLIERLIST,
  GOODS_COMPILEDATA,
  SUPPLIER_GOODS_PASSANDUNPASS,
  SUPPLIER_GOODS_SUBMIT,
  SUPPLIER_GOODS_QIANGGOU_SUBMIT,
  SUPPLIER_DELGOODS,
  GOODSSUPPLIERLIST,
  SUPPLIER_PUTAWAYGOODS
} from "../../constants/api";
import Confirm from "../components/confirm/confirm";
import GzhAuth from "../../components/gzh-auth/gzh-auth";
import './index.scss'
import {vcmonitor} from "../../utils/tools";

type StateProps = {
  listData: any
  drawerShow: any
  search: any
  siteList: any
  goodsList: any
  storeList: any
  productType: any
  loadMoreStatus: any
  active: any
  confirmShow: boolean
  confirmTitle: string
  confirmId: any
  confirmCb: any
  isRefuseOpen: any
  unPassReason: any
  dataType: any
  supplierId: any
  addShow: boolean
}

class productList extends Component {
  state: StateProps = {
    supplierId: null,
    dataType: '',
    unPassReason: '',
    isRefuseOpen: false,
    active: 0,
    loadMoreStatus: 'loading',
    drawerShow: false,
    confirmTitle: '',
    confirmId: null,
    confirmCb: null,
    addShow: false,
    confirmShow: false,
    siteList: [],
    goodsList: [],
    storeList: [],
    productType: [],
    listData: [],
    search: {
      page: 0,
      pageSize: 10
    }
  }

  onReachBottom() {
    this.loadMore()
  }

  loadMore() {
    if (this.state.loadMoreStatus != 'noMore' && this.state.loadMoreStatus != 'loading') {
      const { listData } = this.state;
      const add_date = listData.length > 0 ? listData[listData.length - 1].add_date : "";
      this.setState({loadMoreStatus: 'loading'}, async () => {
        const {search} = this.state;
        search.page++;
        this.setState({
          search
        }, async ()=> await this.getData(search.page, "", add_date));
      })
    }
  }

  async componentDidShow() {
    vcmonitor(this)
    this.reset();
  }

  async componentDidMount() {
    // 产品类型
    const goodsCompiliData = await http.HGet(GOODSCOMPILEDATA, {});
    const productType: any = [];
    for (let i = 0; goodsCompiliData.data[i]; i++) {
      productType.push({
        label: goodsCompiliData.data[i].name,
        value: goodsCompiliData.data[i].name,
        type: goodsCompiliData.data[i].type
      });
    }
    // 所属站点
    const siteApi = await http.HGet(GOODSSITELIST, {
      type: 'move'
    });
    const siteList = siteApi.data.map(item => {
      return {
        label: item.name,
        value: item.id
      }
    })
    this.goodsList();
    this.setState({
      productType,
      siteList
    });
  }

  async goodsList() {
    const res = await http.HGet(SUPPLIER_GOODS_SUPPLIERLIST, {
      type: 'move'
    });
    const goodsList = res.data.map(item => {
      return {
        value: item.id,
        label: item.company
      }
    })
    this.setState({
      goodsList
    });
  }

  async getData(page?: any, type?, add_date?) {
    let {search, siteList, goodsList, storeList, productType, listData} = this.state;
    page = page || 1;
    Taro.showLoading({title: '加载中...'});
    // 20220903: 去掉分页, 增加 add_date
    const res = await http.HGet(SUPPLIER_GOODS_PAGE, {
      ...search,
      type: 'move',
      search_tadpole_site: siteList[search.search_tadpole_site] && siteList[search.search_tadpole_site].value || '',
      search_supplier_id: goodsList[search.search_supplier_id] && goodsList[search.search_supplier_id].value || '',
      search_supplier_checker_group_id: storeList[search.search_supplier_checker_group_id] && storeList[search.search_supplier_checker_group_id].value || '',
      tadpole_goods_type: productType[search.tadpole_goods_type] && productType[search.tadpole_goods_type].value || '',
      page,
      add_date
    });
    // 原分页逻辑
    /*if (res.totalRows <= page * 10) {
      this.setState({
        loadMoreStatus: 'noMore'
      });
    } else {
      this.setState({
        loadMoreStatus: 'more'
      });
    }*/
    // 新分页逻辑: 20220903
    if (res.totalRows !== 10) {
      this.setState({
        loadMoreStatus: 'noMore'
      });
    } else {
      this.setState({
        loadMoreStatus: 'more'
      });
    }
    if (type == 'reset') {
      if (res.data && res.data.length > 0) {
        listData = res.data;
      } else {
        listData = [];
      }

    } else {
      if (res.data && res.data.length > 0) {
        listData = listData.concat(res.data);
      }
    }
    this.setState({
      listData
    });
    Taro.hideLoading();
  }

  // 关闭筛选
  setDrawer(drawerShow) {
    this.setState({
      drawerShow
    });
  }

  // 搜索
  search(key, value) {
    const search = this.state.search;
    search[key] = value;
    this.setState({
      search
    });
    if (key == 'search_supplier_id') {
      const supplier_id = this.state.goodsList[value].value;
      this.getStore(supplier_id);
    }
  }

  // 根据站点获取门店
  getSite() {
    http.HGet(GOODSSUPPLIERLIST, {
      type: 'move'
    }).then(res => {
      const goodsSiteList = res.data.map(item => {
        return {
          value: item.id,
          label: item.company
        }
      })
      this.setState({
        goodsSiteList
      });
    });
  }

  // 获取门店
  getStore(supplier_id) {
    http.HGet(GOODS_COMPILEDATA, {
      supplier_id
    }).then(res => {
      const storeList = res.data.map(item => {
        return {
          value: item.id,
          label: item.name
        }
      });
      this.setState({
        storeList
      });
    });
  }

  // 类型选择
  cur(active) {
    const {search} = this.state;
    search.page = 1;
    search.status = active == 0 ? '' :
      active == 1 ? '待BDM审核' :
        active == 2 ? '待提交' : '审核完成';
    this.setState({
      active,
      search
    }, async ()=>{
      this.getData(search.page, 'reset');
    });
  }

  // 重置
  reset(time: any = 300) {
    const search = this.state.search;
    const search1: any = {};
    search1.page = 1;
    search1.status = search.status;
    search1.pageSize = 10;
    this.setState({
      search: search1,
      loadMoreStatus: 'loading'
    }, async ()=>{
      this.getData(1, 'reset')
    });
  }

  // 搜索筛选
  searchScreen() {
    const {active, search} = this.state;
    const types = active == 0 ? '' :
      active == 1 ? '待BDM审核' :
        active == 2 ? '待提交' : '审核完成';
    search.page = 1;
    this.setState({
      search,
      drawerShow: false
    });
    this.getData(0, 'reset');
  }

  // 显示confirm
  confirmOpen(confirmTitle, confirmId, confirmCb, dataType = '') {
    this.setState({
      confirmTitle,
      confirmId,
      confirmCb,
      dataType
    });
    this.confirmClose(true);
  }

  // 提示框点击确定
  async confirmSuccess() {
    const {confirmCb, confirmId} = this.state;
    confirmCb(confirmId);
  }

  // 提示框点击遮罩层隐藏
  confirmClose(isShow = false) {
    this.setState({
      confirmShow: isShow
    });
  }

  // 通过
  async adoptGoods(goods_id, op = 'pass', unPassReason = '', title = '通过成功') {
    let data = this.state.listData.filter(item => goods_id == item.id);
    this.confirmClose();
    this.reufseShow();
    data = data && data[0];
    http.postCar(SUPPLIER_GOODS_PASSANDUNPASS, {
      type: 'move',
      goods_id,
      op,
      data_type: this.state.dataType,
      unPassReason,
      tadpole_goods_type: data.tadpole_goods_type
    }).then(res => {
      Taro.showToast({title: '操作成功', duration: 1500, icon: 'none'})
      const timer = setTimeout(()=>{
        clearTimeout(timer)
        this.reset();
      },1500)
    })
  }

  // 删除
  async delGoods(goodsId) {
    let data = this.state.listData.filter(item => goodsId == item.id);
    data = data && data[0];
    this.confirmClose();
    const res = await http.postCar(SUPPLIER_DELGOODS, {
      type: 'move',
      goodsId,
      tadpole_goods_type: data.tadpole_goods_type
    });
    if (res) {
      this.reset();
    }
  }

  // 上架
  async putGoods(goodsId, tadpole_goods_type) {
    this.confirmClose();
    const res = await http.postCar(SUPPLIER_PUTAWAYGOODS, {
      type: 'move',
      goodsId,
      tadpole_goods_type
    });
    if (res) {
      this.reset();
    }
  }

  // 提交表单
  async commitGoods(goods_id) {
    let data = this.state.listData.filter(item => goods_id == item.id);
    this.confirmClose();
    data = data && data[0];
    let api
    if (data.tadpole_goods_type === '限时抢购') {
      api = SUPPLIER_GOODS_QIANGGOU_SUBMIT
    } else {
      api = SUPPLIER_GOODS_SUBMIT
    }
    const res = await http.postCar(api, {
      type: 'move',
      goods_id,
      tadpole_goods_type: data.tadpole_goods_type
    });
    if (res) {
      this.reset();
    }
  }

  // 拒绝原因
  reufseChange(value) {
    this.setState({
      unPassReason: value
    });
  }

  // 拒绝显示
  reufseShow(isShow = false, supplierId?, dataType = '') {
    this.setState({
      dataType,
      isRefuseOpen: isShow,
      supplierId,
      unPassReason: ''
    });
  }

  // 拒绝确定
  refuseGoods() {
    const {supplierId, unPassReason} = this.state;
    this.adoptGoods(supplierId, 'unPass', unPassReason, '拒绝成功');
  }

  render() {
    const {addShow, unPassReason, isRefuseOpen, listData, confirmTitle, confirmShow, drawerShow, search, siteList, goodsList, storeList, productType, active} = this.state;
    return (
      <View className='product-list'>
        <GzhAuth />
        <View className='product-list-ap'>
          <View
            className='product-list-ap-item'
            style={active == 0 ? `color:${process.env.mainColor};` : ''}
            onClick={() => this.cur(0)}
          >全部</View>
          <View
            className='product-list-ap-item'
            style={active == 1 ? `color:${process.env.mainColor};` : ''}
            onClick={() => this.cur(1)}
          >审核中</View>
          <View
            className='product-list-ap-item'
            style={active == 2 ? `color:${process.env.mainColor};` : ''}
            onClick={() => this.cur(2)}
          >待提交</View>
          <View
            className='product-list-ap-item'
            style={active == 3 ? `color:${process.env.mainColor};` : ''}
            onClick={() => this.cur(3)}
          >
            已通过
          </View>
          <View>
            <NewIcon
              className='icon iconfont icon-shaixuan-01'
              font='24'
              color='#0bbe7f'
              top='10'
              style='left: -10px;'
              onClick={
                () => {
                  const drawerShow = this.state.drawerShow;
                  this.setState({
                    drawerShow: !drawerShow
                  })
                }
              }
            />
          </View>
        </View>
        <View className='product-list-item-wrap'>
          {
            listData.map((item, index) =>
              <View className='product-list-item' key={index}>
                <View className='product-list-item-right'>{item.process_status}</View>
                <View className='product-list-item-name' style='-webkit-box-orient: vertical;'>{item.name}</View>
                <View className='line' />
                <View className='product-list-item-content'>
                  创建时间：{item.add_date == null ? '' : item.add_date}
                </View>
                <View className='product-list-item-content'>
                  所属站点：{item.sid == null ? '' : item.sid}
                </View>
                <View className='product-list-item-content'>
                  所属商家：{item.supplier_name == null ? '' : item.supplier_name}
                </View>
                {item.tadpole_goods_type !== '邮寄商品' && <View className='product-list-item-content'>
                  所属门店：{item.supplierCheckerGroupName == null ? '' : item.supplierCheckerGroupName}
                </View>}
                <View className='product-list-item-content'>
                  产品类型：{item.tadpole_goods_type == null ? '' : item.tadpole_goods_type}
                </View>
                <View className='product-list-item-content'>
                  {
                    item.refuse_reason && item.process_status == '待提交' && <View className='product-list-item-content'>
                      拒绝原因：{item.refuse_reason}
                    </View>
                  }
                </View>
                {
                  item.add_user && <View className='product-list-item-content'>
                    提交人：{item.add_user}
                  </View>
                }
                {
                  item.editorUser && <View className='product-list-item-content'>
                    编辑：{item.editorUser}
                  </View>
                }
                <View className='product-list-item-btn'>
                  {(item.process_status == '待提交' && item.isbduser == 1) &&
                  <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle
                              onClick={() => Taro.navigateTo({url: '/main/productForm/index?id=' + item.id + "&type=" + encodeURIComponent(item.tadpole_goods_type) + "&sale_style=" + item.sale_style})}
                    >编辑</AtButton>
                  </View>
                  }
                  {(item.process_status == '待提交' && item.isbduser == 1) &&
                  <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle
                              onClick={() => this.confirmOpen('确定要提交吗', item.id, this.commitGoods.bind(this), item.data_type)}
                    >提交</AtButton>
                  </View>
                  }
                  {(item.process_status == '待提交' && item.isbduser == 1) &&
                  <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle
                              onClick={() => this.confirmOpen('确定要删除吗', item.id, this.delGoods.bind(this), item.data_type)}
                    >删除</AtButton>
                  </View>
                  }
                  {(item.process_status == '待BDM审核' && item.role == 2 && item.is_may == 1) &&
                  <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle
                              onClick={() => this.confirmOpen('确定要通过吗', item.id, this.adoptGoods.bind(this), item.data_type)}
                    >通过</AtButton>
                  </View>
                  }
                  {(item.process_status == '待BDM审核' && item.role == 2 && item.is_may == 1) &&
                  <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                    <AtButton size='small' circle onClick={() => this.reufseShow(true, item.id, item.data_type)}>拒绝</AtButton>
                  </View>
                  }
                  {
                    item.process_status != '待提交' && item.tadpole_goods_type !== '串货产品' &&
                    <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                      <AtButton
                        size='small' circle
                        onClick={
                          () => Taro.navigateTo({url: '/main/productDetail/index?id=' + item.id + "&type=" + item.tadpole_goods_type + "&sale_style=" + item.sale_style})
                        }
                      >详情</AtButton>
                    </View>
                  }
                  {
                    item.process_status == '审核完成' && item.isSame == "true" &&
                    <View className='product-list-item-btn-button product-list-item-btn-button-top'>
                      <AtButton size='small' circle
                                onClick={() => Taro.navigateTo({url: '/main/productForm/index?id=' + item.id + "&type=" + encodeURIComponent(item.tadpole_goods_type) + "&sale_style=" + item.sale_style + "&site_list=" + item.site_list + "&operate=copy"})}
                      >复制</AtButton>
                    </View>
                  }
                </View>

                {/* 多站点选择 */}
                <View className='addSite'>
                  {
                    item.urlList.map((items, indexTwo) => {
                      return (
                        <View key={indexTwo}>
                          {
                            (indexTwo < 2 || addShow == true) &&
                            <View className='addSite-lrflex'>
                              <View className={
                                process.env.TARO_ENV === 'h5'? "addSite-lrflex-left_h5": "addSite-lrflex-left"
                              }
                              >{ items.name }</View>
                              <View className='addSite-lrflex-right flexs'>
                                {(item.tadpole_goods_type === '串货产品' || items.process_status == '审核完成' || items.process_status == '上架成功') &&
                                <View className='product-list-item-btn-button' onClick={()=> { Taro.navigateTo({ url: items.url }) }}><AtButton size='small' circle>预览</AtButton>
                                </View>}
                                {(items.process_status == '审核完成' && items.pubCount == 0 && item.isbduser == 1) &&
                                <View className='product-list-item-btn-button'
                                      onClick={() => this.confirmOpen('确定要上架吗', items.id, (id) => {
                                        this.putGoods(id, items.tadpole_goods_type)
                                      })}
                                >
                                  <AtButton size='small' circle>上架</AtButton>
                                </View>
                                }
                              </View>
                            </View>
                          }
                        </View>
                      )
                    })
                  }
                  {item.urlList.length >= 3 && <View
                    className='more'
                    onClick={
                      () => {
                        this.setState({
                          addShow: !addShow
                        })
                      }
                    }
                  >
                    {
                      !addShow &&
                      <View>
                        查看更多
                        <AtIcon value='chevron-down' size='14' color='#B6B6B7'></AtIcon>
                      </View>
                    }
                    {
                      addShow &&
                      <View>
                        隐藏
                        <AtIcon value='chevron-up' size='14' color='#B6B6B7'></AtIcon>
                      </View>
                    }
                  </View>}
                </View>
              </View>)
          }
          {
            listData.length <= 0 && <View className='center'>暂无数据信息</View>
          }
        </View>
        <View
          className={process.env.TARO_ENV === 'h5' ? "addInfo h5-small" : "addInfo"}
          style={`background-color: ${process.env.mainColor}`}
          onClick={
            () => Taro.navigateTo({url: '/main/productForm/index'})
          }
        >增加产品信息 +</View>
        <AtDrawer
          show={drawerShow}
          mask
          onClose={this.setDrawer.bind(this, false)}
          right
          width='70%'
        >
          <View className='scrrent'>
            <ScrollView
              className='scrollview'
              scrollY
              scrollWithAnimation
            >
              <View className='scrrent-item'>商品名称</View>
              <View className='scrrent-item m-b-40 scrrent-item-font-small scrrent-item-border'>
                <Input
                  placeholder='请输入商家名称'
                  onInput={({detail: {value}}) => this.search("search_name", value)}
                  value={search.search_name}
                  className='scrrent-item-font-small'
                />
              </View>
              <View className='scrrent-item'>所属站点</View>
              <View
                className='scrrent-item scrrent-item-font-small scrrent-item-border'
                style={`color: ${search.search_tadpole_site ? '#333' : '#ccc'};`}
              >
                <Picker
                  mode='selector'
                  rangeKey='label'
                  range={siteList}
                  onChange={({detail: {value}}) => this.search("search_tadpole_site", value)}
                  value={search.search_tadpole_site}
                >
                  {siteList[search.search_tadpole_site] && siteList[search.search_tadpole_site].label || "请选择站点"}
                </Picker>
              </View>
              <View className='scrrent-item'>所属商家</View>
              <View
                className='scrrent-item scrrent-item-font-small scrrent-item-border'
                style={`color: ${search.search_supplier_id ? '#333' : '#ccc'};`}
              >
                <Picker
                  mode='selector'
                  rangeKey='label'
                  range={goodsList}
                  onChange={({detail: {value}}) => this.search("search_supplier_id", value)}
                  value={search.search_supplier_id}
                >
                  {goodsList[search.search_supplier_id] && goodsList[search.search_supplier_id].label || "请选择商家"}
                </Picker>
              </View>
              <View className='scrrent-item'>所属门店</View>
              <View
                className='scrrent-item scrrent-item-font-small scrrent-item-border'
                style={`color: ${search.search_supplier_checker_group_id ? '#333' : '#ccc'};`}
              >
                <Picker
                  mode='selector'
                  rangeKey='label'
                  range={storeList}
                  onChange={({detail: {value}}) => this.search("search_supplier_checker_group_id", value)}
                  value={search.search_supplier_checker_group_id}
                >
                  {storeList[search.search_supplier_checker_group_id] && storeList[search.search_supplier_checker_group_id].label || "请选择门店"}
                </Picker>
              </View>
              <View className='scrrent-item'>产品类型</View>
              <View
                className='scrrent-item scrrent-item-font-small scrrent-item-border'
                style={`color: ${search.tadpole_goods_type ? '#333' : '#ccc'};`}
              >
                <Picker
                  mode='selector'
                  rangeKey='label'
                  range={productType}
                  onChange={({detail: {value}}) => this.search("tadpole_goods_type", value)}
                  value={search.tadpole_goods_type}
                >
                  {productType[search.tadpole_goods_type] && productType[search.tadpole_goods_type].label || "请选择产品类型"}
                </Picker>
              </View>
              <View className='scrrent-item'>创建日期起</View>
              <View className='scrrent-item scrrent-item-font-small scrrent-item-border'>
                <Picker mode='date' onChange={({detail: {value}}) => this.search('search_add_Date_start', value)}
                        value={search.search_add_Date_start}
                >
                  {search.search_add_Date_start || "请选择创建日期"}
                </Picker>
              </View>
              <View className='scrrent-item'>创建日期止</View>
              <View className='scrrent-item scrrent-item-font-small scrrent-item-border'>
                <Picker mode='date' onChange={({detail: {value}}) => this.search('search_add_Date_end', value)}
                        value={search.search_add_Date_end}
                >
                  {search.search_add_Date_end || "请选择创建日期"}
                </Picker>
              </View>
              <View className='scrrent-item flex'>
                <View className='scrrent-item-btn' onClick={() => this.reset()}>
                  重置
                </View>
                <View
                  className='scrrent-item-btn'
                  style={`background-color: ${process.env.mainColor}; color: #fff;`}
                  onClick={() => this.searchScreen()}
                >
                  搜索
                </View>
              </View>
            </ScrollView>
          </View>
        </AtDrawer>
        <View onClick={(e) => e.stopPropagation()}>
          {confirmShow && <Confirm
            width='70'
            content={confirmTitle}
            success={() => this.confirmSuccess()}
            cancel={() => this.confirmClose()}
            close={() => this.confirmClose()}
          />}
        </View>
        {isRefuseOpen && <AtModal className='model' isOpened={isRefuseOpen}>
          <AtModalHeader>拒绝原因<AtIcon onClick={() => {
            this.setState({isRefuseOpen: false})
          }} className='close-cla f-r' value='close' size='20' color='#888888'
          /></AtModalHeader>
          <AtModalContent>
            <View className={`${unPassReason == '' ? 'mepty' : 'black'}`}>
              <Textarea
                maxLength={100}
                placeholder='请输入拒绝原因'
                placeholderStyle='color: #c5c5c5;'
                style={`width: 99%; height: 100px; border: solid 1px #c5c5c5; box-sizing: border-box; padding: 10px; ${unPassReason == '' ? 'color: #c5c5c5;' : 'color: #000'}`}
                value={unPassReason}
                onInput={({detail: {value}}) => this.reufseChange(value)}
              />
            </View>
          </AtModalContent>
          <AtModalAction>
            <Button
              className='readed'
              onClick={() => this.refuseGoods()}
              style={`background: ${process.env.mainColor}; color: #fff;`}
            >确定</Button>
          </AtModalAction>
        </AtModal>}
      </View>
    )
  }
}

export default productList as ComponentClass;
